<?php
include __DIR__ . "/config/cors.php";
include __DIR__ . "/database.php";

$cookie = @$_COOKIE['role'];
$uid = @$_POST['uid'];
$password = @$_POST['password'];
$password2 = @$_POST['password2'];

if (!isset($cookie) or $cookie != "admin") {
    echo json_encode([
        "code" => 401,
        "message" => "无权访问！"
    ]);
    exit;
} else if (!isset($password) or $password == "") {
    echo json_encode([
        "code" => 201,
        "message" => "密码不能为空"
    ]);
    exit;
} else if ($password != $password2) {
    echo json_encode([
        "code" => 201,
        "message" => "两次密码不一致"
    ]);
    exit;
}

$db = new DB();
$sql = "select * from user where id = $uid";
$data = $db->selectOne($sql);
if (is_array($data) and count($data) > 0) {
    $username = $data['username'];
    $sql = "update user set password = '$password' where id = $uid";
    if ($db->execute($sql)) {
        echo json_encode([
            "code" => 200,
            "message" => "已重置 ${username} 密码为 ${password}，请尽快修改"
        ]);
    } else {
        echo json_encode([
            "code" => 205,
            "message" => "重置密码失败"
        ]);
    }
} else {
    echo json_encode([
        "code" => 202,
        "message" => "查无此用户"
    ]);
}